<script setup>
import { useForm, router } from '@inertiajs/vue3'
import { computed, ref } from 'vue'
import { 
    ArrowLeftIcon,
    CheckCircleIcon,
    ExclamationCircleIcon,
    ArrowPathIcon,
    FolderIcon
} from '@heroicons/vue/24/outline'
import { useToast } from '@/Composables/useToast'

const props = defineProps({
    category: {
        type: Object,
        required: true
    }
})

const toast = useToast()

const form = useForm({
    name: props.category.name || '',
    slug: props.category.slug || '',
    description: props.category.description || ''
})

const isEditing = computed(() => props.category.id)

// 监听名称变化自动生成 slug
const autoGenerateSlug = ref(!isEditing.value)

const generateSlug = (name) => {
    if (!autoGenerateSlug.value) return
    return name
        .toLowerCase()
        .replace(/\s+/g, '-')
        .replace(/[^\w\-]+/g, '')
}

// 监听名称变化
const handleNameChange = () => {
    if (autoGenerateSlug.value) {
        form.slug = generateSlug(form.name)
    }
}

const submit = () => {
    if (isEditing.value) {
        form.put(route('admin.categories.update', props.category.id), {
            preserveScroll: true,
            onSuccess: () => {
                toast.success('分类更新成功！')
            },
            onError: (errors) => {
                console.error('表单错误：', errors)
                if (errors.error) {
                    toast.error(errors.error)
                } else {
                    toast.error('保存失败，请检查表单信息')
                }
            }
        })
    } else {
        form.post(route('admin.categories.store'), {
            preserveScroll: true,
            onSuccess: () => {
                toast.success('分类创建成功！')
            },
            onError: (errors) => {
                console.error('表单错误：', errors)
                if (errors.error) {
                    toast.error(errors.error)
                } else {
                    toast.error('保存失败，请检查表单信息')
                }
            }
        })
    }
}

// 返回列表
const goBack = () => {
    router.visit(route('admin.categories.index'))
}

// 是否有错误
const hasErrors = computed(() => {
    return Object.keys(form.errors).length > 0
})
</script>

<template>
    <div class="space-y-6">
        <!-- 页面头部 -->
        <div class="flex items-center justify-between">
            <div class="flex items-center gap-x-4">
                <button
                    type="button"
                    @click="goBack"
                    class="inline-flex items-center rounded-md p-2 text-gray-400 hover:text-gray-500 hover:bg-gray-100 transition-colors"
                >
                    <ArrowLeftIcon class="h-5 w-5" />
                    <span class="sr-only">返回</span>
                </button>
                <div>
                    <h1 class="text-3xl font-bold text-gray-900">
                        {{ isEditing ? '编辑分类' : '新建分类' }}
                    </h1>
                    <p class="mt-2 text-sm text-gray-600">
                        {{ isEditing ? '修改分类信息' : '创建一个新的文章分类' }}
                    </p>
                </div>
            </div>
            <button
                type="button"
                @click="submit"
                :disabled="form.processing"
                class="inline-flex items-center gap-x-2 rounded-md bg-orange-600 px-4 py-2 text-sm font-semibold text-white shadow-sm hover:bg-orange-500 focus:outline-none focus:ring-2 focus:ring-orange-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
            >
                <ArrowPathIcon
                    v-if="form.processing"
                    class="h-5 w-5 animate-spin"
                />
                <CheckCircleIcon
                    v-else
                    class="h-5 w-5"
                />
                {{ form.processing ? (isEditing ? '更新中...' : '创建中...') : (isEditing ? '更新分类' : '创建分类') }}
            </button>
        </div>

        <!-- 错误提示 -->
        <div
            v-if="hasErrors"
            class="rounded-md bg-red-50 border border-red-200 p-4"
        >
            <div class="flex">
                <div class="flex-shrink-0">
                    <ExclamationCircleIcon class="h-5 w-5 text-red-400" />
                </div>
                <div class="ml-3">
                    <h3 class="text-sm font-medium text-red-800">表单验证失败</h3>
                    <div class="mt-2 text-sm text-red-700">
                        <ul class="list-disc list-inside space-y-1">
                            <li v-for="(error, field) in form.errors" :key="field">
                                {{ error }}
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>

        <!-- 表单内容 -->
        <form @submit.prevent="submit" class="space-y-8">
            <!-- 基本信息 -->
            <div class="bg-white rounded-lg border border-gray-200 shadow-sm">
                <div class="px-6 py-4 border-b border-gray-200">
                    <div class="flex items-center gap-x-3">
                        <div class="h-10 w-10 rounded-lg bg-orange-100 flex items-center justify-center">
                            <FolderIcon class="h-6 w-6 text-orange-600" />
                        </div>
                        <div>
                            <h2 class="text-lg font-semibold text-gray-900">基本信息</h2>
                            <p class="mt-1 text-sm text-gray-600">填写分类的基本信息</p>
                        </div>
                    </div>
                </div>
                <div class="p-6 space-y-6">
                    <!-- 名称 -->
                    <div>
                        <label for="name" class="block text-sm font-medium text-gray-900 mb-2">
                            名称 <span class="text-red-500">*</span>
                        </label>
                        <input
                            v-model="form.name"
                            @input="handleNameChange"
                            type="text"
                            id="name"
                            class="block w-full rounded-md border border-gray-300 px-3 py-2 text-sm text-gray-900 placeholder:text-gray-400 focus:border-orange-500 focus:outline-none focus:ring-1 focus:ring-orange-500"
                            :class="{ 'border-red-300 focus:border-red-500 focus:ring-red-500': form.errors.name }"
                            placeholder="输入分类名称..."
                        >
                        <p v-if="form.errors.name" class="mt-2 text-sm text-red-600 flex items-center gap-x-1">
                            <ExclamationCircleIcon class="h-4 w-4" />
                            {{ form.errors.name }}
                        </p>
                    </div>

                    <!-- Slug -->
                    <div>
                        <label for="slug" class="block text-sm font-medium text-gray-900 mb-2">
                            Slug <span class="text-red-500">*</span>
                        </label>
                        <div class="flex items-center gap-x-3">
                            <input
                                v-model="form.slug"
                                type="text"
                                id="slug"
                                class="block flex-1 rounded-md border border-gray-300 px-3 py-2 text-sm text-gray-900 placeholder:text-gray-400 focus:border-orange-500 focus:outline-none focus:ring-1 focus:ring-orange-500 font-mono"
                                :class="{ 'border-red-300 focus:border-red-500 focus:ring-red-500': form.errors.slug }"
                                placeholder="分类的 URL 友好标识符..."
                            >
                            <label class="flex items-center gap-x-2 text-sm text-gray-700 cursor-pointer whitespace-nowrap">
                                <input
                                    type="checkbox"
                                    v-model="autoGenerateSlug"
                                    class="h-4 w-4 rounded border-gray-300 text-orange-600 focus:ring-orange-500"
                                >
                                <span>自动生成</span>
                            </label>
                        </div>
                        <p v-if="form.errors.slug" class="mt-2 text-sm text-red-600 flex items-center gap-x-1">
                            <ExclamationCircleIcon class="h-4 w-4" />
                            {{ form.errors.slug }}
                        </p>
                        <p v-else class="mt-1 text-xs text-gray-500">
                            URL 友好标识符，用于生成分类链接
                        </p>
                    </div>

                    <!-- 描述 -->
                    <div>
                        <label for="description" class="block text-sm font-medium text-gray-900 mb-2">
                            描述
                        </label>
                        <textarea
                            v-model="form.description"
                            id="description"
                            rows="4"
                            class="block w-full rounded-md border border-gray-300 px-3 py-2 text-sm text-gray-900 placeholder:text-gray-400 focus:border-orange-500 focus:outline-none focus:ring-1 focus:ring-orange-500"
                            :class="{ 'border-red-300 focus:border-red-500 focus:ring-red-500': form.errors.description }"
                            placeholder="输入分类描述（可选）..."
                        />
                        <p v-if="form.errors.description" class="mt-2 text-sm text-red-600 flex items-center gap-x-1">
                            <ExclamationCircleIcon class="h-4 w-4" />
                            {{ form.errors.description }}
                        </p>
                    </div>
                </div>
            </div>
        </form>
    </div>
</template> 